package com.youlai.boot.core.tenant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.core.tenant.mapper.GlobalUserMapper;
import com.youlai.boot.core.tenant.model.entity.GlobalUser;
import com.youlai.boot.core.tenant.service.GlobalUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 全局用户服务实现类
 *
 * @author haoxr
 * @since 3.0.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GlobalUserServiceImpl extends ServiceImpl<GlobalUserMapper, GlobalUser> implements GlobalUserService {

    @Override
    public List<GlobalUser> getUserTenantsByOpenId(String openId) {
        if (StrUtil.isBlank(openId)) {
            return List.of();
        }
        return baseMapper.selectByOpenId(openId);
    }

    @Override
    public List<GlobalUser> getUserTenantsByMobile(String mobile) {
        if (StrUtil.isBlank(mobile)) {
            return List.of();
        }
        return baseMapper.selectByMobile(mobile);
    }

    @Override
    public List<GlobalUser> getUserTenantsByEmail(String email) {
        if (StrUtil.isBlank(email)) {
            return List.of();
        }
        return baseMapper.selectByEmail(email);
    }

    @Override
    public GlobalUser getPrimaryTenantByOpenId(String openId) {
        if (StrUtil.isBlank(openId)) {
            return null;
        }
        return baseMapper.selectPrimaryByOpenId(openId);
    }

    @Override
    public GlobalUser getPrimaryTenantByMobile(String mobile) {
        if (StrUtil.isBlank(mobile)) {
            return null;
        }
        return baseMapper.selectPrimaryByMobile(mobile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrUpdateGlobalUser(String openId, String unionId, String mobile, 
                                           Long tenantId, Long userId, String username, String nickname) {
        if (tenantId == null || userId == null) {
            log.warn("创建全局用户失败：tenantId 或 userId 为空");
            return false;
        }

        if (StrUtil.isBlank(openId) && StrUtil.isBlank(mobile)) {
            log.warn("创建全局用户失败：openId 和 mobile 都为空");
            return false;
        }

        // 构建查询条件
        LambdaQueryWrapper<GlobalUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GlobalUser::getTenantId, tenantId);
        
        if (StrUtil.isNotBlank(openId)) {
            queryWrapper.eq(GlobalUser::getOpenId, openId);
        } else if (StrUtil.isNotBlank(mobile)) {
            queryWrapper.eq(GlobalUser::getMobile, mobile);
        }

        // 查询是否已存在
        GlobalUser existUser = baseMapper.selectOne(queryWrapper);

        if (existUser != null) {
            // 更新现有记录
            boolean updated = false;
            if (StrUtil.isNotBlank(unionId) && !unionId.equals(existUser.getUnionId())) {
                existUser.setUnionId(unionId);
                updated = true;
            }
            if (StrUtil.isNotBlank(mobile) && !mobile.equals(existUser.getMobile())) {
                existUser.setMobile(mobile);
                updated = true;
            }
            if (StrUtil.isNotBlank(username) && !username.equals(existUser.getUsername())) {
                existUser.setUsername(username);
                updated = true;
            }
            if (StrUtil.isNotBlank(nickname) && !nickname.equals(existUser.getNickname())) {
                existUser.setNickname(nickname);
                updated = true;
            }
            if (userId != null && !userId.equals(existUser.getUserId())) {
                existUser.setUserId(userId);
                updated = true;
            }

            if (updated) {
                existUser.setUpdateTime(LocalDateTime.now());
                baseMapper.updateById(existUser);
                log.info("更新全局用户：id={}, tenantId={}, userId={}", existUser.getId(), tenantId, userId);
            }
            return true;
        }

        // 创建新记录
        GlobalUser globalUser = new GlobalUser();
        globalUser.setOpenId(openId);
        globalUser.setUnionId(unionId);
        globalUser.setMobile(mobile);
        globalUser.setTenantId(tenantId);
        globalUser.setUserId(userId);
        globalUser.setUsername(username);
        globalUser.setNickname(nickname);
        globalUser.setStatus(1);
        
        // 判断是否为主账号（如果该用户没有其他租户记录，则为主账号）
        LambdaQueryWrapper<GlobalUser> checkWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(openId)) {
            checkWrapper.eq(GlobalUser::getOpenId, openId);
        } else if (StrUtil.isNotBlank(mobile)) {
            checkWrapper.eq(GlobalUser::getMobile, mobile);
        }
        long count = baseMapper.selectCount(checkWrapper);
        globalUser.setIsPrimary(count == 0 ? 1 : 0);
        
        globalUser.setCreateTime(LocalDateTime.now());
        globalUser.setIsDeleted(0);

        baseMapper.insert(globalUser);
        log.info("创建全局用户：openId={}, unionId={}, mobile={}, tenantId={}, userId={}, isPrimary={}", 
                openId, unionId, mobile, tenantId, userId, globalUser.getIsPrimary());

        return true;
    }
}

